package felix.fuse.mount.service;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class S3Service implements BaseService {

    private final Logger log = LoggerFactory.getLogger(getClass());

    private String accessKey = "admin";

    private String secretKey = "admin123";

    private String endpoint = "http://192.168.56.100:9000";

    private int connectionTimeout = 30000;

    private int socketTimeout = 30000;

    private int maxKey = 10000;

    private int maxErrorRetry = 0;

    private String protocol_config = "http";

    private Protocol protocol;

    public AmazonS3 s3Client = null;

    public final static String empty = ".empty";

    @Override
    public void init() {
    }

    public void close() {
        if (s3Client != null) {
            s3Client.shutdown();
            s3Client = null;
        }
    }

    @Override
    public void destroy() {
        this.close();
    }

    public boolean reConnectS3() {
        if (!this.isInit()) {
            this.connect();
        }
        try {
            this.listBuckets();
            ContextContainer.get(LogEventService.class).post("连接服务器成功");
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if (e.getMessage().contains("403") && e.getMessage().contains("Forbidden")) {
                ContextContainer.get(LogEventService.class).post("连接服务器失败,用户名或密码错误");
            } else {
                ContextContainer.get(LogEventService.class).post("连接服务器失败,错误信息为:" + e.getMessage());
            }
            return false;
        }
    }

    public void set(String accessKey, String secretKey, String endpoint) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.endpoint = endpoint;
        if (endpoint != null && endpoint.contains("https")) {
            this.protocol_config = "https";
        } else {
            this.protocol_config = "http";
        }
        this.init();
    }

    public void connect() {
        if ("https".equalsIgnoreCase(protocol_config)) {
            protocol = Protocol.HTTPS;
        } else {
            protocol = Protocol.HTTP;
        }

        AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setProtocol(protocol);
        clientConfig.setMaxConnections(50);
        if (socketTimeout > 0) {
            clientConfig.setSocketTimeout(socketTimeout);
        }
        if (maxErrorRetry >= 0) {
            clientConfig.setMaxErrorRetry(maxErrorRetry);
        }
        if (connectionTimeout > 0) {
            clientConfig.setConnectionTimeout(connectionTimeout);
        }
        s3Client = AmazonS3ClientBuilder.standard().withClientConfiguration(clientConfig)
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withEndpointConfiguration(new EndpointConfiguration(endpoint, "")).withPathStyleAccessEnabled(true)
                .build();
    }

    public boolean isInit() {
        return s3Client != null;
    }

    public List<String> listBuckets() {
        List<Bucket> buckets = s3Client.listBuckets();
        return buckets.stream().map(bucket -> bucket.getName()).collect(Collectors.toList());
    }

    public ObjectListing listSub(String bucketName, String path) {
        String key = this.getKey(path);
        ListObjectsRequest req = new ListObjectsRequest();
        req.setMaxKeys(maxKey);
        req.setBucketName(bucketName);
        if (key.length() == 0) {
            req.setPrefix(null);
        } else {
            req.setPrefix(key + "/");
        }
        req.setDelimiter("/");
        try {
            ObjectListing list = s3Client.listObjects(req);
            return list;
        } catch (AmazonS3Exception e) {
            if (e.getStatusCode() == 404) {
                return null;
            } else {
                log.error(e.getMessage());
                return null;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }

    }

    public boolean renameFile(String bucketName, String oldPath, String newPath) {
        String key = this.getKey(oldPath);
        String newKey = this.getKey(newPath);
        try {
            CopyObjectRequest copyObjRequest = new CopyObjectRequest(bucketName,
                    key, bucketName, newKey);
            s3Client.copyObject(copyObjRequest);
            s3Client.deleteObject(bucketName, key);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public boolean renameDir(String bucketName, String oldPath, String newPath) {
        String key = this.getKey(oldPath);
        String newKey = this.getKey(newPath);
        try {
            ListObjectsRequest req = new ListObjectsRequest();
            req.setMaxKeys(maxKey);
            req.setBucketName(bucketName);
            req.setPrefix(key + "/");
            ObjectListing list = s3Client.listObjects(req);
            List<S3ObjectSummary> summaries = list.getObjectSummaries();
            List<String> deleteKeys = new ArrayList<>();
            for (S3ObjectSummary summary : summaries) {
                String oldKey = summary.getKey();
                String renameKey = oldKey.replace(key, newKey);
                log.info("rename {} {}", oldKey, renameKey);
                CopyObjectRequest copyObjRequest = new CopyObjectRequest(bucketName,
                        oldKey, bucketName, renameKey);
                s3Client.copyObject(copyObjRequest);
                deleteKeys.add(oldKey);
            }
            for (String deleteKey : deleteKeys) {
                s3Client.deleteObject(bucketName, deleteKey);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }

    }

    public InitiateMultipartUploadResult initiateMultipartUploadResult(String bucketName, String path) {
        String key = this.getKey(path);
        InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, key);
        try {
            InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(request);
            return initResponse;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }

    }

    public UploadPartResult uploadPart(String bucketName, String path, int number, byte[] bytes, InitiateMultipartUploadResult initResponse) {
        String key = this.getKey(path);
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        UploadPartRequest uploadRequest = new UploadPartRequest()
                .withBucketName(bucketName)
                .withKey(key)
                .withUploadId(initResponse.getUploadId())
                .withPartNumber(number)
                .withInputStream(in)
                .withPartSize(bytes.length);
        try {
            UploadPartResult uploadPartResult = s3Client.uploadPart(uploadRequest);
            return uploadPartResult;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public void completeMultipartUploadRequest(String bucketName, String path, InitiateMultipartUploadResult initResponse, List<PartETag> partETags) {
        String key = this.getKey(path);
        try {
            CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(bucketName, key,
                    initResponse.getUploadId(), partETags);
            s3Client.completeMultipartUpload(compRequest);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    public boolean putObject(String bucketName, String path, byte[] bytes) {
        String key = this.getKey(path);
        ObjectMetadata metadata = new ObjectMetadata();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new ByteArrayInputStream(bytes), metadata);
        try {
            s3Client.putObject(putObjectRequest);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public boolean fileExist(String bucketName, String path) {
        String key = this.getKey(path);
        try {
            return s3Client.doesObjectExist(bucketName, key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return true;
        }
    }

    public void mkdir(String bucketName, String path) {
        path = getEmptyFile(path);
        String key = this.getKey(path);
        try {
            boolean objectExist = s3Client.doesObjectExist(bucketName, key);
            if (objectExist) {
                return;
            }
            PutObjectResult putObjectResult = s3Client.putObject(bucketName, key, empty);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public boolean rmdir(String bucketName, String path) {
        String key = this.getKey(path);
        try {
            Boolean isEmpty = this.isEmptyPath(bucketName, path);
            if (isEmpty == null) {
                return false;
            }
            if (!isEmpty) {
                return false;
            }
            key = getEmptyFile(key);
            s3Client.deleteObject(bucketName, key);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public boolean deleteObject(String bucketName, String path) {
        String key = this.getKey(path);
        try {
            s3Client.deleteObject(bucketName, key);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public Boolean isEmptyPath(String bucketName, String path) {
        ObjectListing list = this.listSub(bucketName, path);
        if (list == null) {
            return null;
        }
        List<S3ObjectSummary> summaries = list.getObjectSummaries();
        if (summaries.size() == 0) {
            return true;
        }
        for (S3ObjectSummary summary : summaries) {
            if (summary.getKey().endsWith(empty)) {
                return true;
            }
        }
        return false;
    }

    public S3Object openFile(String bucketName, String path, long offset) {
        String key = this.getKey(path);
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        return s3Client.getObject(getObjectRequest);
    }

    public byte[] read(String bucketName, String path, long size, long offset) {
        String key = this.getKey(path);
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        getObjectRequest.setRange(offset, offset + size - 1);
        S3Object s3Object = null;
        S3ObjectInputStream in = null;
        try {
            s3Object = s3Client.getObject(getObjectRequest);
            in = s3Object.getObjectContent();
            return IOUtils.toByteArray(in);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (s3Object != null) {
                try {
                    s3Object.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    public ObjectMetadata getObjectMetadata(String bucketName, String path) {
        String key = this.getKey(path);
        return s3Client.getObjectMetadata(bucketName, key);
    }

    /**
     * 获取空文件夹，主要是由于s3没有空文件夹的语意，所以需要与一个空文件关联
     *
     * @param path
     * @return
     */
    private String getEmptyFile(String path) {
        return path + "/" + empty;
    }

    private String getKey(String path) {
        if (path.startsWith("/")) {
            return path.substring(1);
        } else {
            return path;
        }
    }


}
